from django import http
from django.shortcuts import render
from django.views import View
from django.core.cache import cache
from apps.areas.models import Area
from utils.response_code import RETCODE


class AreasView(View):
    def get(self,request):
        #接收参数
        area_id = request.GET.get('area_id')

        #判断
        if not area_id:
            province_list = cache.get("province_list")
            if not province_list:
                provinces = Area.objects.filter(parent_id__isnull=True)
                province_list =[{'id':pro.id, 'name':pro.name} for pro in provinces]
                cache.set('province_list',province_list,3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:
            sub_data = cache.get("sub_data" + area_id)
            if not sub_data:
                parent_medel = Area.objects.get(id = area_id)
                # subs = Area.objects.filter(parent_id=area_id)
                subs = parent_medel.subs.all()

                sub_list = [{'id':sub.id, 'name':sub.name} for sub in subs]

                sub_data = {
                    'id':parent_medel.id,
                    'name':parent_medel.name,
                    'subs':sub_list
                }
                cache.set('sub_data' + area_id,sub_data,3600)
        #返回
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})
